package com.webex.ta.hydra.gui.action;

import com.webex.ta.hydra.core.TestResult;
import com.webex.ta.hydra.core.engine.ResultCollector;
import com.webex.ta.hydra.gui.GuiPackage;
import com.webex.ta.hydra.gui.util.FileDialoger;
import com.webex.ta.hydra.util.HydraUtils;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.io.FileUtils;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-15
 * Time: 10:51:38
 */
public class ExportResultAction implements ActionHandler {
    private static Set<String> commands = new HashSet<String>();

    static {
        commands.add(ActionNames.EXPORT_RESULT);
    }

    public Set<String> getActionNames() {
        return commands;
    }

    public void doAction(ActionEvent e) {
        List<TestResult> results = ResultCollector.getInstance().getResults();
        if (results == null || results.size() == 0) {
            JOptionPane.showMessageDialog(GuiPackage.getInstance().getIdeFrame(), "No test result to export");
            return;
        }

        JFileChooser chooser = FileDialoger.promptToSaveFile("report.html");
    	if (chooser == null)
			return;

        String reportPath = chooser.getSelectedFile().getAbsolutePath();

        Template t = HydraUtils.getFreeMarkerTemplate("detail_report.ftl");
        Map root = new HashMap();
        root.put("results", results);
        OutputStream out = null;
        try {
            File reportFile = new File(reportPath);
            out = new FileOutputStream(reportFile);
            t.process(root, new OutputStreamWriter(out));

            String dir = reportFile.getParent();
            FileUtils.copyFile(new File(HydraUtils.getHydraTemplatePath(), "up.gif"),
                    new File(dir, "up.gif"));
            FileUtils.copyFile(new File(HydraUtils.getHydraTemplatePath(), "down.gif"),
                    new File(dir, "down.gif"));
        } catch (TemplateException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            HydraUtils.closeQuietly(out);
        }
    }
}
